package com.yl.chainStore.services.impl.sick

import com.alibaba.fastjson.JSONObject
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper
import com.baomidou.mybatisplus.core.toolkit.Wrappers
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.yl.chainStore.common.Constants
import com.yl.chainStore.common.enums.Status
import com.yl.chainStore.common.enums.TypeEnum
import com.yl.chainStore.entity.pay.PayCustomerOrder
import com.yl.chainStore.entity.sick.*
import com.yl.chainStore.entity.user.CompanyUserOperationLog
import com.yl.chainStore.entity.user.CompanyUserOperationLogDetail
import com.yl.chainStore.mapper.pay.PayCustomerOrderMapper
import com.yl.chainStore.mapper.sick.*
import com.yl.chainStore.mapper.user.CompanyUserOperationLogDetailMapper
import com.yl.chainStore.mapper.user.CompanyUserOperationLogMapper
import com.yl.chainStore.pojo.vo.sick.CustomerSubscribeLogOperationVo
import com.yl.chainStore.pojo.vo.sick.SickMedicalHistorySelectVo
import com.yl.chainStore.pojo.vo.sick.SickMedicalRecordsDetailToStatusVo
import com.yl.chainStore.pojo.vo.sick.SickMedicalRecordsDetailUpdateVo
import com.yl.chainStore.pojo.vo.user.CompanyUserOperationLogSelectVo
import com.yl.chainStore.services.ICompanyUserOperationLogService
import com.yl.chainStore.services.ICustomerInfoService
import com.yl.chainStore.services.sick.ICustomerSubscribeLogService
import com.yl.chainStore.services.sick.ISickMedicalRecordsService
import com.yl.chainStore.util.dateFormat
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import com.yl.message.common.MessageType
import com.yl.message.service.ISendMessageService
import com.yl.message.websocket.WebSocketMessageType
import com.yl.message.websocket.WebSocketMessageVo
import com.yl.users.common.getId
import com.yl.users.services.ICompanyDeptService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.*

/**
 * 就诊记录
 */
@Service
class SickMedicalRecordsServiceImpl(
	private val sickMedicalRecordsMapper: SickMedicalRecordsMapper,
	private val sickMedicalRecordsDetailMapper: SickMedicalRecordsDetailMapper,
	private val payCustomerOrderMapper: PayCustomerOrderMapper,
	private val sickMedicalHistoryMapper: SickMedicalHistoryMapper,
	private val sickMedicalRecordsDetailStatusUpdateLogMapper: SickMedicalRecordsDetailStatusUpdateLogMapper,
	private val companyUserOperationLogMapper: CompanyUserOperationLogMapper,
	private val companyUserOperationLogDetailMapper: CompanyUserOperationLogDetailMapper,
	private val customerSubscribeLogMapper:CustomerSubscribeLogMapper
) : ISickMedicalRecordsService {

	companion object {
		private val log = LoggerFactory.getLogger(ISickMedicalRecordsService::class.java)
	}

	@Autowired
	private lateinit var companyDeptService: ICompanyDeptService

	@Autowired
	private lateinit var iSendMessageService: ISendMessageService

	@Autowired
	private lateinit var iCustomerSubscribeLogService: ICustomerSubscribeLogService

	@Autowired
	private lateinit var iCustomerInfoService: ICustomerInfoService

	@Autowired
	lateinit var iCompanyUserOperationLogService: ICompanyUserOperationLogService

	override fun getRecord(recordId: Long): SickMedicalRecords? {
		log.info("就诊记录 ==> 获取基本信息：recordId：{}", recordId)
		return sickMedicalRecordsMapper.selectById(recordId)
	}

	override fun saveDetail(detail: SickMedicalRecordsDetail): ResponseBody {
		log.info("就诊记录 ==> 保存就诊记录明细：detail：{}", detail)
		val record = getRecord(detail.recordId)
		if (detail.id != 0L) {
			val oldObj = sickMedicalRecordsDetailMapper.selectById(detail.id) ?: return returnError(
				ErrorCode.DATA_IS_NOT_FIND,
				"保存失败，请刷新重试"
			)

			sickMedicalRecordsDetailMapper.updateById(detail)
			iCompanyUserOperationLogService.addLog(
				associatedId = detail.id,
				modelType = TypeEnum.COMPANY_USER_OPERATION_LOG_MODEL_TYPE_RECORD,
				tableType = TypeEnum.COMPANY_USER_OPERATION_LOG_TABLE_TYPE_RECORD_DETAIL,
				updateType = TypeEnum.COMPANY_USER_OPERATION_LOG_UPDATE_TYPE_UPDATE,
				beforeObj = oldObj,
				afterObj = detail,
				customerId = record?.customerId,
				createUserId = getContext().userId
			)
		} else {
			sickMedicalRecordsDetailMapper.insert(detail)
			iCompanyUserOperationLogService.addLog(
				associatedId = detail.id,
				modelType = TypeEnum.COMPANY_USER_OPERATION_LOG_MODEL_TYPE_RECORD,
				tableType = TypeEnum.COMPANY_USER_OPERATION_LOG_TABLE_TYPE_RECORD_DETAIL,
				updateType = TypeEnum.COMPANY_USER_OPERATION_LOG_UPDATE_TYPE_NEW_ADD,
				beforeObj = null,
				afterObj = detail,
				customerId = record?.customerId,
				createUserId = getContext().userId
			)
			if (dateFormat(Date()) == dateFormat(detail.toDay)) {
				//通知前端刷新侧边栏
				val lastLoginHavePremUsers = companyDeptService.getLastLoginHavePremUsers(
					getContext().subCompanyId,
					Constants.UserPermCode.TODAY_RECORD
				)
				val vo = WebSocketMessageVo(
					messageType = WebSocketMessageType.REFRESH_COUNT,
					data = Constants.CountRefresh.TODAY_RECORD
				)
				for (u in lastLoginHavePremUsers) {
					iSendMessageService.sendMessageToCompanyUserHaveType(
						JSONObject(0),
						JSONObject.toJSON(vo) as JSONObject,
						MessageType.WEBSOCKET,
						u.id
					)
				}
			}
		}

		return returnSuccess()
	}

	override fun createSubscribeLogByDetail(detail: SickMedicalRecordsDetail): ResponseBody {
		val record = getRecord(detail.recordId) ?: return returnError(
			ErrorCode.DATA_SAVE_FAILED, "未找到就诊记录"
		)
		val subscribeLog = CustomerSubscribeLog(
			id = 0,
			customerId = record.customerId,
			clinicType = detail.detailType,
			subscribeTime = detail.startTime,
			timeLength = 30,
			consultantId = detail.secondaryUserId,
			doctorId = detail.masterUserId,
			remark = detail.remark
		)
		val addSubscribeLog = iCustomerInfoService.addSubscribeLog(subscribeLog)
		if (addSubscribeLog.bodyIsError()) {
			return addSubscribeLog
		}
		val detailByDetailId = getDetailByDetailId(detail.id)
		if (detailByDetailId != null) {
			detailByDetailId.subscribeLogId = subscribeLog.id
			sickMedicalRecordsDetailMapper.updateById(detailByDetailId)
		}

		return returnSuccess()
	}

	override fun getOrder(recordId: Long): List<PayCustomerOrder> {
		log.info("就诊记录 ==> 获取关联订单：recordId：{}", recordId)
		return payCustomerOrderMapper.selectList(
			Wrappers.query<PayCustomerOrder?>()
				.eq("record_id", recordId)
		)
	}

	override fun setRecordToOngoing(recordId: Long): ResponseBody {
		log.info("就诊记录 ==> 设置处理中状态：recordId：{}", recordId)
		val records = sickMedicalRecordsMapper.selectById(recordId) ?: return returnError(
			ErrorCode.OPERATION_DATA_ERROR,
			"未找到就诊记录"
		)
		if (records.status == Status.COMPLETE) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "此次就诊已完成")
		}
		records.status = Status.ONGOING
		sickMedicalRecordsMapper.updateById(records)
		return returnSuccess()
	}

	override fun setRecordToPause(recordId: Long): ResponseBody {
		log.info("就诊记录 ==> 设置完成状态：recordId：{}", recordId)
		val records = sickMedicalRecordsMapper.selectById(recordId) ?: return returnError(
			ErrorCode.OPERATION_DATA_ERROR,
			"未找到就诊记录"
		)
		if (records.status == Status.COMPLETE) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "此次就诊已完成")
		}
		records.status = Status.PUSH
		sickMedicalRecordsMapper.updateById(records)
		return returnSuccess()
	}

	override fun setRecordToEnd(recordId: Long): ResponseBody {
		log.info("就诊记录 ==> 设置结束状态：recordId：{}", recordId)
		val records = sickMedicalRecordsMapper.selectById(recordId) ?: return returnError(
			ErrorCode.OPERATION_DATA_ERROR,
			"未找到就诊记录"
		)
		if (records.status == Status.COMPLETE) {
			return returnSuccess()
		}
		records.status = Status.PUSH
		sickMedicalRecordsMapper.updateById(records)
		return returnSuccess()
	}


	override fun getHistoryPage(
		page: Page<SickMedicalHistory>,
		vo: SickMedicalHistorySelectVo
	): Page<SickMedicalHistory> {
		log.info("就诊记录 ==> 获取关联的病历记录：page：{}，vo:{}", page, vo)
		return sickMedicalHistoryMapper.getHistoryPage(page, vo)
	}

	override fun getDetailByDetailId(id: Long): SickMedicalRecordsDetail? {
		val detail = sickMedicalRecordsDetailMapper.selectById(id)
		if (detail?.recordId != null) {
			detail.record = sickMedicalRecordsMapper.selectById(detail.recordId)
		}
		return detail
	}


	override fun updateDetailByDetailId(vo: SickMedicalRecordsDetailUpdateVo): ResponseBody {
		val detailByDetailId = getDetailByDetailId(vo.id) ?: return returnError(
			ErrorCode.DATA_IS_NOT_FIND,
			"未找到就诊信息，请刷新重试"
		)
		val record = getRecord(detailByDetailId.recordId)
		val oldLog = detailByDetailId.copy()
//		detailByDetailId.recordId = detail.recordId


//		detailByDetailId.medicalSourcesType = vo.medicalSourcesType
//		detailByDetailId.medicalSources = vo.medicalSources
//		detailByDetailId.masterUserId = vo.masterUserId
//		detailByDetailId.secondaryUserId = vo.secondaryUserId
//		detailByDetailId.remark = vo.remark
//		sickMedicalRecordsDetailMapper.updateById(detailByDetailId)
		val updateWrapper=UpdateWrapper<SickMedicalRecordsDetail>()
		updateWrapper.eq("id",detailByDetailId.id)
				.set("medical_sources_type",vo.medicalSourcesType)
				.set("medical_sources",vo.medicalSources)
				.set("master_user_id",vo.masterUserId)
				.set("secondary_user_id",vo.secondaryUserId)
				.set("remark",vo.remark)
		if(vo.registeredType != null){
			updateWrapper.set("detail_type",vo.registeredType!!)
		}
		sickMedicalRecordsDetailMapper.update(null,updateWrapper)

		iCompanyUserOperationLogService.addLog(
			associatedId = oldLog.id,
			modelType = TypeEnum.COMPANY_USER_OPERATION_LOG_MODEL_TYPE_RECORD,
			tableType = TypeEnum.COMPANY_USER_OPERATION_LOG_TABLE_TYPE_RECORD_DETAIL,
			updateType = TypeEnum.COMPANY_USER_OPERATION_LOG_UPDATE_TYPE_UPDATE,
			beforeObj = oldLog,
			afterObj = detailByDetailId,
			customerId = record?.customerId,
			createUserId = getContext().userId
		)
		return returnSuccess()
	}

	override fun updateDetailBySubscribeLog(subscribeLog: CustomerSubscribeLog): ResponseBody {
		// TODO: 2021/11/26 是否状态也要修改
		val recordsDetail = iCustomerSubscribeLogService.getRecordsDetailBySubscribeId(subscribeLog.id)?.copy()
			?: return returnSuccess()
		if(subscribeLog.itemIds != null && subscribeLog.itemIds != ""){
			recordsDetail.content = iCustomerSubscribeLogService.getSubscribeItemsByIdsStr(subscribeLog.itemIdsShow!!)
		}
		recordsDetail.detailType = subscribeLog.clinicType
		recordsDetail.startTime = subscribeLog.subscribeTime
		recordsDetail.secondaryUserId = subscribeLog.consultantId
		recordsDetail.masterUserId = subscribeLog.doctorId
		recordsDetail.remark = subscribeLog.remark
		recordsDetail.toDay = subscribeLog.subscribeTime
		updateDetailAllField(recordsDetail)
		return returnSuccess()
	}

	override fun updateDetailAllField(detail: SickMedicalRecordsDetail): ResponseBody {
		val oldLog = getDetailByDetailId(detail.id) ?: return returnError(
			ErrorCode.DATA_IS_NOT_FIND,
			"未找到就诊信息，请刷新重试"
		)
		val record = getRecord(oldLog.recordId)
		val updateWrapper = UpdateWrapper<SickMedicalRecordsDetail>()
		updateWrapper.eq("id",detail.id)
			.set("start_time",detail.startTime)
			.set("end_time",detail.endTime)
			.set("to_day",detail.toDay)
			.set("secondary_user_id",detail.secondaryUserId)
			.set("master_user_id",detail.masterUserId)
			.set("content",detail.content)
			.set("record_id",detail.recordId)
			.set("other",detail.other)
			.set("dept_id",detail.deptId)
			.set("detail_type",detail.detailType)
			.set("medical_sources_type",detail.medicalSourcesType)
			.set("medical_sources",detail.medicalSources)
			.set("registered_num",detail.registeredNum)
			.set("status",detail.status)
			.set("remark",detail.remark)
			.set("subscribe_log_id",detail.subscribeLogId)

		sickMedicalRecordsDetailMapper.update(null,updateWrapper)
		iCompanyUserOperationLogService.addLog(
			associatedId = oldLog.id,
			modelType = TypeEnum.COMPANY_USER_OPERATION_LOG_MODEL_TYPE_RECORD,
			tableType = TypeEnum.COMPANY_USER_OPERATION_LOG_TABLE_TYPE_RECORD_DETAIL,
			updateType = TypeEnum.COMPANY_USER_OPERATION_LOG_UPDATE_TYPE_UPDATE,
			beforeObj = oldLog,
			afterObj = detail,
			customerId = record?.customerId,
			createUserId = getContext().userId
		)
		return returnSuccess()
	}

	override fun customerCanCome(detailId: Long): ResponseBody {
		val any = sickMedicalRecordsDetailMapper.selectById(detailId) ?: return returnError(
			ErrorCode.DATA_IS_NOT_FIND,
			"未找到就诊信息，请刷新重试"
		)
		return customerCanCome(any)
	}

	override fun customerCanCome(detail: SickMedicalRecordsDetail): ResponseBody {
		val newDetail = detail.copy()
		newDetail.status = Status.NON_ARRIVAL

		return updateDetailAllField(newDetail)
	}

	override fun customerCome(detailId: Long): ResponseBody {
		val any = sickMedicalRecordsDetailMapper.selectById(detailId)
		if (any == null) {
			returnError(
				ErrorCode.DATA_IS_NOT_FIND,
				"未找到就诊记录，请刷新重试"
			)
		}
		return customerCome(any)
	}

	override fun customerCome(detail: SickMedicalRecordsDetail): ResponseBody {
		val newDetail = detail.copy()
		if (newDetail.status != Status.NON_ARRIVAL) {
			returnError(
				ErrorCode.PARAMETER_FORMAT_ERROR,
				"该信息已被处理，请刷新重试"
			)
		}
		newDetail.status = Status.WAIT_AUDIT
		updateDetailAllField(newDetail)
		val selectById = sickMedicalRecordsMapper.selectById(newDetail.recordId)
		if (selectById != null) {
			iCustomerInfoService.refreshLastRecordsDetailId(selectById.customerId)
		}
		if (dateFormat(Date()) == dateFormat(detail.toDay)) {
			//通知前端刷新侧边栏
			val lastLoginHavePremUsers = companyDeptService.getLastLoginHavePremUsers(
				getContext().subCompanyId,
				Constants.UserPermCode.TODAY_RECORD
			)
			val vo = WebSocketMessageVo(
				messageType = WebSocketMessageType.REFRESH_COUNT,
				data = Constants.CountRefresh.TODAY_RECORD
			)
			for (u in lastLoginHavePremUsers) {
				iSendMessageService.sendMessageToCompanyUserHaveType(
					JSONObject(0),
					JSONObject.toJSON(vo) as JSONObject,
					MessageType.WEBSOCKET,
					u.id
				)
			}
		}
		return returnSuccess()
	}

	override fun customerVisiting(detailId: Long): ResponseBody {
		val any = sickMedicalRecordsDetailMapper.selectById(detailId)
		if (any == null) {
			returnError(
				ErrorCode.DATA_IS_NOT_FIND,
				"未找到就诊记录，请刷新重试"
			)
		}


		return customerVisiting(any)
	}

	override fun customerVisiting(detail: SickMedicalRecordsDetail): ResponseBody {
		val newDetail = detail.copy()
		if (newDetail.status != Status.WAIT_AUDIT) {
			returnError(
				ErrorCode.PARAMETER_FORMAT_ERROR,
				"该信息已被处理，请刷新重试"
			)
		}
		newDetail.status = Status.IN_THE_TREATMENT
		updateDetailAllField(newDetail)
		return returnSuccess()
	}

	override fun customerVisitingEnd(detailId: Long): ResponseBody {
		val any = sickMedicalRecordsDetailMapper.selectById(detailId)
		if (any == null) {
			returnError(
				ErrorCode.DATA_IS_NOT_FIND,
				"未找到就诊记录，请刷新重试"
			)
		}
		return customerVisitingEnd(any)
	}

	override fun customerVisitingEnd(detail: SickMedicalRecordsDetail): ResponseBody {
		val newDetail = detail.copy()
		if (newDetail.status != Status.IN_THE_TREATMENT) {
			returnError(
				ErrorCode.PARAMETER_FORMAT_ERROR,
				"该信息已被处理，请刷新重试"
			)
		}
		newDetail.status = Status.COMPLETE_TREATMENT

		return 	updateDetailAllField(newDetail)
	}

	override fun customerOrderPayEnd(detailId: Long): ResponseBody {
		val any = sickMedicalRecordsDetailMapper.selectById(detailId)
		if (any == null) {
			returnError(
				ErrorCode.DATA_IS_NOT_FIND,
				"未找到就诊记录，请刷新重试"
			)
		}
		return customerOrderPayEnd(any)
	}

	override fun customerOrderPayEnd(detail: SickMedicalRecordsDetail): ResponseBody {
		val newDetail = detail.copy()
		if (newDetail.status != Status.COMPLETE_TREATMENT) {
			returnError(
				ErrorCode.PARAMETER_FORMAT_ERROR,
				"该信息已被处理，请刷新重试"
			)
		}
		newDetail.status = Status.ORDER_PAY_END
		return updateDetailAllField(newDetail)
	}

	override fun detailOver(detailId: Long): ResponseBody {
		val any = sickMedicalRecordsDetailMapper.selectById(detailId)
		if (any == null) {
			returnError(
				ErrorCode.DATA_IS_NOT_FIND,
				"未找到就诊记录，请刷新重试"
			)
		}

		return detailOver(any)

	}

	override fun detailOver(detail: SickMedicalRecordsDetail): ResponseBody {
		val newDetail = detail.copy()
		if (newDetail.status != Status.ORDER_PAY_END) {
			returnError(
				ErrorCode.PARAMETER_FORMAT_ERROR,
				"该信息已被处理，请刷新重试"
			)
		}
		newDetail.status = Status.LEAVE
		return updateDetailAllField(newDetail)
	}

	override fun detailToStatus(vo: SickMedicalRecordsDetailToStatusVo): ResponseBody {
		val any = sickMedicalRecordsDetailMapper.selectById(vo.id)
		if (any == null) {
			returnError(
				ErrorCode.DATA_IS_NOT_FIND,
				"未找到就诊记录，请刷新重试"
			)
		}

		if (any.status.code >= vo.toStatus.code) {
			returnError(
				ErrorCode.PARAMETER_FORMAT_ERROR,
				"该信息已被处理，请刷新重试"
			)
		}
		val updateLog = SickMedicalRecordsDetailStatusUpdateLog(
			id = 0,
			recordDetailId = any.id,
			beforeStatus = any.status,
			afterStatus = vo.toStatus,
		)
		if (any.status == Status.SUBSCRIBE) {
			//预约的话  记录就诊记录状态改变  预约状态改变
			customerCanCome(any)
			any.status = Status.NON_ARRIVAL
			if (any.subscribeLogId != null) {
				iCustomerSubscribeLogService.completeLog(CustomerSubscribeLogOperationVo(id = any.subscribeLogId!!))
			}
		}
		if (any.status == Status.NON_ARRIVAL) {

			val customerCome = customerCome(any)
			any.status = Status.WAIT_AUDIT
			if (customerCome.bodyIsError()) {
				return customerCome
			} else if (vo.toStatus == Status.WAIT_AUDIT) {
				sickMedicalRecordsDetailStatusUpdateLogMapper.insert(updateLog)
				return customerCome
			}
		}
		if (any.status == Status.WAIT_AUDIT) {
			val customerVisiting = customerVisiting(any)
			any.status = Status.IN_THE_TREATMENT
			if (customerVisiting.bodyIsError()) {
				return customerVisiting
			} else if (vo.toStatus == Status.IN_THE_TREATMENT) {
				sickMedicalRecordsDetailStatusUpdateLogMapper.insert(updateLog)
				return customerVisiting
			}
		}

		if (any.status == Status.IN_THE_TREATMENT) {
			val customerVisitingEnd = customerVisitingEnd(any)
			any.status = Status.COMPLETE_TREATMENT
			if (customerVisitingEnd.bodyIsError()) {
				return customerVisitingEnd
			} else if (vo.toStatus == Status.COMPLETE_TREATMENT) {
				sickMedicalRecordsDetailStatusUpdateLogMapper.insert(updateLog)
				return customerVisitingEnd
			}
		}

		if (any.status == Status.COMPLETE_TREATMENT) {
			val customerVisitingEnd = customerOrderPayEnd(any)
			any.status = Status.ORDER_PAY_END
			if (customerVisitingEnd.bodyIsError()) {
				return customerVisitingEnd
			} else if (vo.toStatus == Status.ORDER_PAY_END) {
				sickMedicalRecordsDetailStatusUpdateLogMapper.insert(updateLog)
				return customerVisitingEnd
			}
		}
		val detailOver = detailOver(any)
		if (detailOver.bodyIsError()) {
			return detailOver
		}
		sickMedicalRecordsDetailStatusUpdateLogMapper.insert(updateLog)
		return returnSuccess()
	}

	override fun detailSetHistoryId(detailId: Long, historyId: Long): ResponseBody {
		val detail = sickMedicalRecordsDetailMapper.selectById(detailId)?:return returnError(ErrorCode.DATA_IS_NOT_FIND,"未找到就诊记录")
		detail.historyId = historyId
		sickMedicalRecordsDetailMapper.updateById(detail)
		return returnSuccess()
	}

	override fun backDetailStatus(id: Long): ResponseBody {
		val selectList = sickMedicalRecordsDetailStatusUpdateLogMapper.selectList(
			Wrappers.query<SickMedicalRecordsDetailStatusUpdateLog?>().eq("record_detail_id", id).eq("use_back", 0)
				.orderByDesc("create_time")
		)
		if (selectList.isEmpty()) {
			//没有操作记录 （就诊记录变成预约，  预约记录变成未确认）
			return cancelRecordDetail(id)
		}

		val updateLog = selectList[0]
		updateLog.useBack = 1
		if (updateLog.beforeStatus == Status.SUBSCRIBE) {
			return cancelRecordDetail(id)
		}
		val sickMedicalRecordsDetail = sickMedicalRecordsDetailMapper.selectById(id) ?: return returnError(
			ErrorCode.DATA_IS_NOT_FIND,
			"未找到该记录，请刷新重试"
		)
		val newDetail = sickMedicalRecordsDetail.copy()
		newDetail.status = updateLog.beforeStatus
		updateDetailAllField(newDetail)
		sickMedicalRecordsDetailStatusUpdateLogMapper.updateById(updateLog)
		if (dateFormat(Date()) == dateFormat(sickMedicalRecordsDetail.toDay)) {
			//通知前端刷新侧边栏
			val lastLoginHavePremUsers = companyDeptService.getLastLoginHavePremUsers(
				getContext().subCompanyId,
				Constants.UserPermCode.TODAY_RECORD
			)
			val vo = WebSocketMessageVo(
				messageType = WebSocketMessageType.REFRESH_COUNT,
				data = Constants.CountRefresh.TODAY_RECORD
			)
			for (u in lastLoginHavePremUsers) {
				iSendMessageService.sendMessageToCompanyUserHaveType(
					JSONObject(0),
					JSONObject.toJSON(vo) as JSONObject,
					MessageType.WEBSOCKET,
					u.id
				)
			}
		}

		return returnSuccess()
	}

	override fun cancelRecordDetail(id: Long): ResponseBody {
		val sickMedicalRecordsDetail = sickMedicalRecordsDetailMapper.selectById(id) ?: return returnError(
			ErrorCode.DATA_IS_NOT_FIND,
			"未找到该记录，请刷新重试"
		)
		val newDetail = sickMedicalRecordsDetail.copy()
		newDetail.status = Status.SUBSCRIBE
		updateDetailAllField(newDetail)
		if (sickMedicalRecordsDetail.subscribeLogId != null) {
			iCustomerSubscribeLogService.backToNewAdd(sickMedicalRecordsDetail.subscribeLogId!!)
		} else {
			createSubscribeLogByDetail(sickMedicalRecordsDetail)
		}

		val selectById = sickMedicalRecordsMapper.selectById(sickMedicalRecordsDetail.recordId)
		if (selectById != null) {
			iCustomerInfoService.refreshLastRecordsDetailId(selectById.customerId)
		}
		return returnSuccess()
	}

	override fun onlyCancelRecordDetail(id: Long): ResponseBody {
		val sickMedicalRecordsDetail = sickMedicalRecordsDetailMapper.selectById(id) ?: return returnError(
			ErrorCode.DATA_IS_NOT_FIND,
			"未找到该记录，请刷新重试"
		)
		val newDetail = sickMedicalRecordsDetail.copy()
		newDetail.status = Status.CANCEL
		updateDetailAllField(newDetail)
		return returnSuccess()
	}

	override fun delDetail(id: Long): ResponseBody {
		val selectById =
			sickMedicalRecordsDetailMapper.selectById(id) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND, "未找到该就诊记录")
		return delDetail(selectById)
	}

	override fun delDetail(detail: SickMedicalRecordsDetail): ResponseBody {
		val oldLog = sickMedicalRecordsDetailMapper.selectById(detail.id)?:return returnError(
			ErrorCode.DATA_IS_NOT_FIND,"未找到就诊记录"
		)
		val record = getRecord(oldLog.recordId)
		if (detail.status != Status.NON_ARRIVAL) {
			return returnError(ErrorCode.OPERATION_DATA_ERROR, "该就诊记录已被处理")
		}
		sickMedicalRecordsDetailMapper.deleteById(detail.id)

		if(detail.subscribeLogId != null){
			customerSubscribeLogMapper.selectById(detail.subscribeLogId)
		}


		iCompanyUserOperationLogService.addLog(
			associatedId = oldLog.id,
			modelType = TypeEnum.COMPANY_USER_OPERATION_LOG_MODEL_TYPE_RECORD,
			tableType = TypeEnum.COMPANY_USER_OPERATION_LOG_TABLE_TYPE_RECORD_DETAIL,
			updateType = TypeEnum.COMPANY_USER_OPERATION_LOG_UPDATE_TYPE_UPDATE,
			beforeObj = oldLog,
			afterObj = null,
			customerId = record?.customerId,
			createUserId = getContext().userId
		)
		if (dateFormat(Date()) == dateFormat(detail.toDay)) {
			//通知前端刷新侧边栏
			val lastLoginHavePremUsers = companyDeptService.getLastLoginHavePremUsers(
				getContext().subCompanyId,
				Constants.UserPermCode.TODAY_RECORD
			)
			val vo = WebSocketMessageVo(
				messageType = WebSocketMessageType.REFRESH_COUNT,
				data = Constants.CountRefresh.TODAY_RECORD
			)
			for (u in lastLoginHavePremUsers) {
				iSendMessageService.sendMessageToCompanyUserHaveType(
					JSONObject(0),
					JSONObject.toJSON(vo) as JSONObject,
					MessageType.WEBSOCKET,
					u.id
				)
			}
		}
		return returnSuccess()
	}

	override fun getRecordDetailUpdateLog(id: Long): List<CompanyUserOperationLog> {
		val selectLogList = companyUserOperationLogMapper.selectLogList(
			CompanyUserOperationLogSelectVo(
				associatedId = id,
				modelType = TypeEnum.COMPANY_USER_OPERATION_LOG_MODEL_TYPE_RECORD,
				tableType = TypeEnum.COMPANY_USER_OPERATION_LOG_TABLE_TYPE_RECORD_DETAIL,
			)
		)
		for(opLog in selectLogList){
			opLog.details = companyUserOperationLogDetailMapper.selectList(
				Wrappers.query<CompanyUserOperationLogDetail?>().eq(
					"log_id",opLog.id
				)
			)
		}

		return selectLogList
	}
}
